package io.github.talelin.latticy.drools;

import io.github.talelin.latticy.LatticyApplication;
import io.github.talelin.latticy.bo.CalculationVO;
import io.github.talelin.latticy.bo.CreditCardApplyVO;
import io.github.talelin.latticy.bo.Student;
import io.github.talelin.latticy.bo.StudentVO;
import io.github.talelin.latticy.common.pojo.DroolsConfigEntity;
import org.drools.core.io.impl.UrlResource;
import org.drools.decisiontable.InputType;
import org.drools.decisiontable.SpreadsheetCompiler;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.api.KieServices;
import org.kie.api.builder.KieModule;
import org.kie.api.builder.KieRepository;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.internal.utils.KieHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;


/**
 * @authoer:wulongbo
 * @createDate:2022/7/7
 * @description:
 */

@RunWith(SpringRunner.class)
@SpringBootTest(classes = LatticyApplication.class)
public class DroolsTest2 {

    @Autowired
    private DroolsConfigEntity droolsConfigEntity;

    @Test
    public void test1() throws Exception {
        //通过此URL可以访问到maven仓库中的jar包
        //URL地址构成：http://ip地址:Tomcat端口号/WorkBench工程名/maven2/坐标/版本号/xxx.jar
        String url = droolsConfigEntity.getUrls().get(0);
        KieServices kieServices = KieServices.Factory.get();
        //通过Resource资源对象加载jar包
        UrlResource resource = (UrlResource) kieServices.getResources().newUrlResource(url);
        //通过Workbench提供的服务来访问maven仓库中的jar包资源，需要先进行Workbench的认证
        resource.setUsername(droolsConfigEntity.getUsername());
        resource.setPassword(droolsConfigEntity.getPassword());
        resource.setBasicAuthentication(droolsConfigEntity.getBasicAuthentication());

        //将资源转换为输入流，通过此输入流可以读取jar包数据
        InputStream inputStream = resource.getInputStream();

        //创建仓库对象，仓库对象中保存Drools的规则信息
        KieRepository repository = kieServices.getRepository();

        //通过输入流读取maven仓库中的jar包数据，包装成KieModule模块添加到仓库中
        KieModule kieModule =
                repository.
                        addKieModule(kieServices.getResources().newInputStreamResource(inputStream));

        //基于KieModule模块创建容器对象，从容器中可以获取session会话
        KieContainer kieContainer = kieServices.newKieContainer(kieModule.getReleaseId());
        KieSession session = kieContainer.newKieSession();
        StudentVO person = new StudentVO();
        person.setAge(10);
        person.setName("张三");
        session.insert(person);

        session.fireAllRules();
        session.dispose();
    }

    @Test
    public void testCalculate() throws Exception {
        //通过此URL可以访问到maven仓库中的jar包
        //URL地址构成：http://ip地址:Tomcat端口号/WorkBench工程名/maven2/坐标/版本号/xxx.jar
        String url = droolsConfigEntity.getUrls().get(2);
        KieServices kieServices = KieServices.Factory.get();
        //通过Resource资源对象加载jar包
        UrlResource resource = (UrlResource) kieServices.getResources().newUrlResource(url);
        //通过Workbench提供的服务来访问maven仓库中的jar包资源，需要先进行Workbench的认证
        resource.setUsername(droolsConfigEntity.getUsername());
        resource.setPassword(droolsConfigEntity.getPassword());
        resource.setBasicAuthentication(droolsConfigEntity.getBasicAuthentication());

        //将资源转换为输入流，通过此输入流可以读取jar包数据
        InputStream inputStream = resource.getInputStream();

        //创建仓库对象，仓库对象中保存Drools的规则信息
        KieRepository repository = kieServices.getRepository();

        //通过输入流读取maven仓库中的jar包数据，包装成KieModule模块添加到仓库中
        KieModule kieModule =
                repository.
                        addKieModule(kieServices.getResources().newInputStreamResource(inputStream));

        //基于KieModule模块创建容器对象，从容器中可以获取session会话
        KieContainer kieContainer = kieServices.newKieContainer(kieModule.getReleaseId());
        KieSession session = kieContainer.newKieSession();
        CalculationVO calculationVO = new CalculationVO();
        calculationVO.setWage(10000d);
        session.insert(calculationVO);
        session.fireAllRules();
        session.dispose();
    }


    @Test
    public void testCreditCardApply() throws Exception {
        //通过此URL可以访问到maven仓库中的jar包
        //URL地址构成：http://ip地址:Tomcat端口号/WorkBench工程名/maven2/坐标/版本号/xxx.jar
        String url = droolsConfigEntity.getUrls().get(3);
        KieServices kieServices = KieServices.Factory.get();
        //通过Resource资源对象加载jar包
        UrlResource resource = (UrlResource) kieServices.getResources().newUrlResource(url);
        //通过Workbench提供的服务来访问maven仓库中的jar包资源，需要先进行Workbench的认证
        resource.setUsername(droolsConfigEntity.getUsername());
        resource.setPassword(droolsConfigEntity.getPassword());
        resource.setBasicAuthentication(droolsConfigEntity.getBasicAuthentication());

        //将资源转换为输入流，通过此输入流可以读取jar包数据
        InputStream inputStream = resource.getInputStream();

        //创建仓库对象，仓库对象中保存Drools的规则信息
        KieRepository repository = kieServices.getRepository();

        //通过输入流读取maven仓库中的jar包数据，包装成KieModule模块添加到仓库中
        KieModule kieModule =
                repository.
                        addKieModule(kieServices.getResources().newInputStreamResource(inputStream));

        //基于KieModule模块创建容器对象，从容器中可以获取session会话
        KieContainer kieContainer = kieServices.newKieContainer(kieModule.getReleaseId());
        KieSession session = kieContainer.newKieSession();
        CreditCardApplyVO creditCardApplyVO = new CreditCardApplyVO();
        creditCardApplyVO.setName("张三");
        creditCardApplyVO.setSex("男");
        creditCardApplyVO.setAddress("深圳");
        creditCardApplyVO.setAge(20);
        creditCardApplyVO.setEducation("专科以下");
        creditCardApplyVO.setHasHouse(false);
        creditCardApplyVO.setHasCar(false);
        creditCardApplyVO.setTelephone("13549553864");
        creditCardApplyVO.setHasCreditCardCount(0);
        creditCardApplyVO.setMonthlyIncome(10001D);
        session.insert(creditCardApplyVO);
        session.fireAllRules();

        System.out.println("信用卡额度:" + creditCardApplyVO.getQuota());
        session.dispose();
    }

    @Test
    public void testExcel2Drl() throws Exception {
//        Resource resource = ResourceFactory.newClassPathResource("rules/decision/tables/student-score.xlsx", "UTF-8");
//        ClassPathResource resource = new ClassPathResource("rules/decision/tables/student-score.xlsx");
//        InputStream inputStream = resource.getInputStream();
//        SpreadsheetCompiler compiler = new SpreadsheetCompiler();
//        String drl = compiler.compile(inputStream, InputType.XLS);
//        System.out.println("决策表转换的drl内容为:" + drl);
        String realPath = "E:\\googledown\\student-score.xlsx";//指定决策表xls文件的磁盘路径
        File file = new File(realPath);
        InputStream is = new FileInputStream(file);
        SpreadsheetCompiler compiler = new SpreadsheetCompiler();
        String drl = compiler.compile(is, InputType.XLS);
        System.out.println(drl);
    }

    @Test
    public void testDrlOneStudent() throws Exception {
        String realPath = "E:\\googledown\\student-score.xlsx";//指定决策表xls文件的磁盘路径
        File file = new File(realPath);
        InputStream is = new FileInputStream(file);
        SpreadsheetCompiler compiler = new SpreadsheetCompiler();
        String drl = compiler.compile(is, InputType.XLS);
        System.out.println(drl);
        KieHelper kieHelper = new KieHelper();
        kieHelper.addContent(drl, ResourceType.DRL);
        KieSession session = kieHelper.build().newKieSession();
        Student student = new Student();
        student.setName("张三");
        student.setScore(20);
        StringBuilder result = new StringBuilder();
        session.setGlobal("resultsInfo", result);
        session.insert(student);
//        session.getAgenda().getAgendaGroup("sign").setFocus();
        session.fireAllRules();
        session.dispose();
    }

    @Test
    public void testStudentList() throws Exception {
        String realPath = "E:\\googledown\\student-score.xlsx";//指定决策表xls文件的磁盘路径
        File file = new File(realPath);
        InputStream is = new FileInputStream(file);
        SpreadsheetCompiler compiler = new SpreadsheetCompiler();
        String drl = compiler.compile(is, InputType.XLS);

        System.out.println(drl);
        KieHelper kieHelper = new KieHelper();
        kieHelper.addContent(drl, ResourceType.DRL);
        KieSession session = kieHelper.build().newKieSession();
        // 张三虽然只得20分，但是根据规则判断，结果应该是  优
        invokedDecisionTable(session, new Student("张三", 20));
        // 李四虽然只得20分，但是根据规则判断，结果应该是  一般
        invokedDecisionTable(session, new Student("李四", 20));
        // 李四得75分，但是根据规则判断，结果应该是  良好
        invokedDecisionTable(session, new Student("李四", 75));
        // 王五得59分，但是根据规则判断，结果应该是  不及格
        invokedDecisionTable(session, new Student("王五", 59));
        // 赵六得20分，但是根据规则判断，结果应该是  一般
        invokedDecisionTable(session, new Student("赵六", 65));
        // 钱七得20分，但是根据规则判断，结果应该是  良好
        invokedDecisionTable(session, new Student("钱七", 75));
        // 李八得20分，但是根据规则判断，结果应该是  优
        invokedDecisionTable(session, new Student("李八", 95));
        session.dispose();
    }

    public static void invokedDecisionTable(KieSession session, Student student) {
        StringBuilder result = new StringBuilder();
        session.setGlobal("resultsInfo",result);
        session.insert(student);
        session.fireAllRules();
        System.out.println("规则执行结果：" + result);
    }


}
